package cn.edu.ctgu.junitTest2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Properties;

public class Configuration {
    private Properties props = new Properties();

    /**
     * 读取属性配置文件
     *
     * @param confFile
     */
    public void fromFile(File confFile) {
        try(FileInputStream in = new FileInputStream(confFile);){
            props.load(new InputStreamReader(in,StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new ValueParseException("配置文件解析错误");
        }
    }

    /**
     * 获取键值
     *
     * @param key
     * @return value
     */
    public String getProp(String key) {
        return props.getProperty(key);
    }

    /**
     * 获取布尔类型键值
     *
     * @param key
     * @return value
     */
    public boolean getBoolean(String key) {
        String value = props.getProperty(key);
        if ("true".equalsIgnoreCase(value)) {
            return true;
        }
        if ("false".equalsIgnoreCase(value)) {
            return false;
        }
        throw new ValueParseException("键值不存在");
    }

    /**
     * 获取布尔类型值(默认)
     *
     * @param key
     * @return value
     */
    public Boolean getBooleanWithDefault(String key,Boolean defaultValue){
        Boolean value;
        try {
            value = getBoolean(key);
        }catch (ValueParseException e){
            value=defaultValue;
        }
        return value;
    }

    /**
     * 获取整数类型键值
     *
     * @param key
     * @return value
     */
    public Integer getInt(String key,int defaultValue){
        Integer value;
        String number;
        number=getProp(key);
        if(number==null){
            value=defaultValue;
        }
        else{
            value= Integer.valueOf(number);
        }
        return value;
    }

    /**
     * 获取日期类型键值
     *
     * @param key
     * @return value
     */
    public LocalDate getDate(String key, LocalDate defaultValue){
        LocalDate value = null;
        String date;
        date=getProp(key);
        if(date==null){
            return defaultValue;
        }
        value=LocalDate.parse(date);
        return value;
    }
}
